<?php

class dbTableHelper extends helperBase {
	
	var $engine = 'MyISAM';
	/*
	function install($tables, $backupDir = null) {
		$this->sterilizeTables(&$tables);
		foreach($tables as $table) {
			$model = &$this->m->$table;
			if($model->dbLink() && !$model->owned()) {
				$this->installTable(&$model, $backupDir);
			}
		}
	}
	*/
	function install($model, $backupDir = null) {
		$tableName = $model->getName();
		$query = 'CREATE TABLE `'.$this->aether->config->get('database', 'name').'`.`'.$tableName.'` ('.NL;
		$first = true;
		$cols = $model->getCols();
		foreach($cols as $name => &$col) {
			if(is_object($col)) {
				$this->install(&$col, $backupDir);
			} else {
				if($first) {
					$first = false;
				} else {
					$query .= ','.NL;
				}
				$query .= TAB.'`'.$name.'` '.$col['type'];
				if(isset($col['length'])) {
					$query .= '('.$col['length'].')';
				}
				if($col['unsigned']) {
					$query .= ' UNSIGNED';
				}
				if($col['unique']) {
					$query .= ' UNIQUE';
				}
				if($col['notNull']) {
					$query .= ' NOT NULL';
				}
				if($col['primaryKey']) {
					$query .= ','.NL.TAB.'PRIMARY KEY (`'.$name.'`)';
				}
				if($col['index']) {
					$query .= ', '.NL.TAB.'INDEX (`'.$name.'`)';
				}
			}
		}
		$query .= NL.')'.NL.'ENGINE = '.$this->engine.';';
		$this->aether->db->query($query);

		$fn = 'app/backups/'.$backupDir.'/'.$tableName.'.dump';
		if(file_exists($fn)) {
			$query = 'LOAD DATA LOCAL INFILE \''.$fn.'\' INTO TABLE `'.$tableName.'`';
			$this->aether->db->query($query);
		}

		if($model->isStable()) {
			$this->install($model->SL(), $backupDir);
		}
	}

	function backup($tables) {
		$this->sterilizeTables(&$tables);
		$set = time();
		mkdir('app/backups/'.$set);
		foreach($tables as $table) {
			$this->backupTable($this->m->$table, $set);
		}
	}
	
	function backupTable(&$model, $set) {
		$fn = '/tmp/'.$set.$model->getName().'.dump';
		$query = 'SELECT * FROM `'.$model->getName().'` INTO OUTFILE \''.$fn.'\'';
		$this->aether->db->query($query);
		for($i = 0; !file_exists($fn); $i++) {
			if($i>6) {
				die(NL.'Backup timeout!');
			}
			usleep(100000);
			echo '.';
			clearstatcache();
		}
		rename($fn, 'app/backups/'.$set.'/'.$model->getName().'.dump');
		$cols = $model->getCols();
		foreach($cols as $name => &$col) {
			if(is_object($col)) {
				$this->backupTable(&$col, $set);
			}
		}
		if($model->isStable()) {
			$this->backupTable($model->SL(), $set);
		}
	}

/*
CREATE TABLE `aetherarin`.`test` (
  `id` INT UNSIGNED NOT NULL,
  `key` VARCHAR(16)  NOT NULL,
  `value` VARCHAR(256)  NOT NULL,
  `updated_at` TIMESAETHERP  NOT NULL,
  `created_at` TIMESAETHERP  NOT NULL,
  PRIMARY KEY (`id`)
)
ENGINE = MyISAM;
*/

	function sterilizeTables($tables) {
		if($tables=='all')
			$tables = $this->getAllModels();
		if(is_string($tables))
			$tables = array($tables);
		$this->aether->loader->load($tables);
	}
	
	function getTableArg($id, $args) {
		if($id=='all') {
			return 'all';
		} else {
			return $args['t'];
		}
	}
	
	function getAllModels() {
		$return = array();
		$dh = opendir('app/models/');
		while ($file = readdir($dh)) {
			if($file[0]!='.'&&$file!='..') {
				$return[$dh.$file] = str_replace('Model.php','',$file);
			}
		}
		closedir($dh);
		$dh = opendir('core/models/');
		while ($file = readdir($dh)) {
			if($file[0]!='.'&&$file!='..') {
				$return[$dh.$file] = str_replace('Model.php','',$file);
			}
		}
		closedir($dh);

		return $return;
	}
	
	function uninstall($tables) {
		$this->sterilizeTables(&$tables);
		foreach($tables as $table) {
			$this->uninstallTable($this->m->$table);
		}
	}
	
	function uninstallTable(&$model) {
		$cols = $model->getCols();
		foreach($cols as $name => $col) {
			if(is_object($col)) {
				$this->uninstallTable(&$col);
			}
		}
		
		if(!$this->aether->db->query('DROP TABLE IF EXISTS `'.$model->getName().'`')) {
			die('MySQL error: '.mysql_error());
		}
	
		if($model->isStable()) {
			$this->uninstallTable($model->SL());
		}
	}
	
}

?>
